﻿package com.shuqi.activity;

import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.shuqi.activity.adapter.ShelfScanAdapter;
import com.shuqi.activity.viewport.BottomDialog;
import com.shuqi.activity.viewport.FileManageTitle;
import com.shuqi.activity.viewport.ToastDialog;
import com.shuqi.application.ShuqiApplication;
import com.shuqi.common.EnterBookContent;
import com.shuqi.common.utils.Log4an;
import com.shuqi.common.utils.ScanLocalFolderTools;
import com.shuqi.common.utils.Util;
import com.shuqi.controller.R;
import com.shuqi.database.dao.impl.BookMarkInfoDao;
import com.shuqi.database.model.BookMarkInfo;
import com.shuqi.statistics.StatisticsEventID;
import com.shuqi.statistics.StatisticsUtils;

/**
 * 本地文件管理类
 * 
 * @author Jianda.Yang
 * 
 * @Date 2014-1-18 下午2:41:25
 */
public class BookShelfFileMangementAcitvity extends ActivityBase implements OnClickListener {

    private static final String TAG = "BookShelfFileMangementAcitvity";
    /** 扫描中dialog */
    // private final int DIALOG_SCANING = 1;

    private ShelfScanAdapter listAdapter;
    private List<Map<String, Object>> listdata;
    private List<Map<String, Object>> listdataTemp;
    private ListView listView;

    private TextView currentPathView; // 显示路径的titleView

    private TextView mBackParentTextView; // 显示上一级的titleView

    private String rootpath;// 总路径
    private String currentpath;// 当前路径
    private int searchType; // 0，正常浏览；1搜索txt;2搜索umd;3搜索epub;4模糊搜索；5搜索.sqb.zip；6搜索.sqd.zip;7当前文件夹下搜索
    private String needFileSuffix;// 关键字

    private boolean canusesdcard = true;

    private View scanBottom;
    private TextView sureButton;

    private Set<String> mAlreadyMarksSet = new HashSet<String>();

    private FileManageTitle mTitle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_shelf_scan);
        loadData();
        mTitle = (FileManageTitle) findViewById(R.id.title);
        mTitle.setImageListener(this);
        listView = (ListView) findViewById(R.id.scan_listview);
        setScrollBar(listView, R.drawable.fast_bar_normal);
        scanBottom = findViewById(R.id.layout_scan_bottom);
        findViewById(R.id.cancle_button).setOnClickListener(this);
        sureButton = (TextView) findViewById(R.id.sure_button);
        sureButton.setEnabled(true);
        sureButton.setOnClickListener(this);
        currentPathView = (TextView) findViewById(R.id.scan_currentpath);
        mBackParentTextView = (TextView) findViewById(R.id.scan_currentpath_right_tv);

        init();
        listAdapter = new ShelfScanAdapter(this, listdata, mAlreadyMarksSet);

        currentPathView.setText(currentpath);
        listView.setAdapter(listAdapter);
        bindListener();
        refresh();
    }

    private void init() {
        // 初始化数据
        if (listdata == null) {
            listdata = new ArrayList<Map<String, Object>>();
        } else {
            listdata.clear();
        }
        if (listdataTemp == null) {
            listdataTemp = new ArrayList<Map<String, Object>>();
        } else {
            listdataTemp.clear();
        }
        if (TextUtils.isEmpty(rootpath)) {
            rootpath = Environment.getExternalStorageDirectory().getPath();
        }
        if (TextUtils.isEmpty(currentpath)) {
            currentpath = rootpath;
        }
    }

    public void onResume() {
        super.onResume();
    }


    private void bindListener() {
        // findViewById(R.id.btn_undo_search).setOnClickListener(this);
        // listView.setOnItemClickListener(this);
        mBackParentTextView.setOnClickListener(this);
    }

    private BottomDialog dialog;
    private TextView smartScan;// 智能扫描
    private TextView txtScan;
    private TextView epubScan;
    private TextView umdScan;

    private void initDialog(View v) {
        smartScan = (TextView) v.findViewById(R.id.view_dialog_smartscan_tv);
        txtScan = (TextView) v.findViewById(R.id.view_dialog_txtscan_tv);
        epubScan = (TextView) v.findViewById(R.id.view_dialog_epubscan_tv);
        umdScan = (TextView) v.findViewById(R.id.view_dialog_umdscan_tv);
        smartScan.setOnClickListener(this);
        txtScan.setOnClickListener(this);
        epubScan.setOnClickListener(this);
        umdScan.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.cancle_button:
                listAdapter.cancelBooks();
                listAdapter.notifyDataSetChanged();
                scanBottom.setVisibility(View.GONE);
                listView.setPadding(0, 0, 0, 0);
                break;
            case R.id.sure_button:// 导入按钮
                listAdapter.importBooks();
                scanBottom.setVisibility(View.GONE);
                listView.setPadding(0, 0, 0, 0);
                break;
            // case R.id.btn_undo_search:
            // findViewById(R.id.btn_undo_search).setVisibility(View.GONE);
            // findViewById(R.id.bookshelf_scan_img).setVisibility(View.VISIBLE);
            // // 隐藏软键盘
            // Util.inputMethodControl(this, false);
            // break;
            case R.id.title_right:
                float scale = getResources().getDisplayMetrics().density;

                if (dialog == null) {
                    View view = View.inflate(this, R.layout.view_dialog_bookshelf_scan, null);

                    dialog = new BottomDialog(this, view);
                    initDialog(view);
                    // smartScan.setTextSize((float) (17*(scale/3.0)));
                    // 判断设备的像素浓度，小于等于1.5 时将字体大小设置为15sp,大于1.5时 为17sp（保持原来的不变）
                    if (scale <= 1.5) {
                        smartScan.setTextSize(15);
                        txtScan.setTextSize(15);
                        epubScan.setTextSize(15);
                        umdScan.setTextSize(15);
                    }


                    view.setOnClickListener(this);
                }

                if (dialog != null && !dialog.isShowing() && !isFinishing()) {
                    dialog.show();
                }
                break;
            case R.id.title_right_wifi_iv:// wifi导书
                gotoWifi();
                StatisticsUtils.onEvent(this, StatisticsEventID.BOOKSHELF_WIFI);
                break;
            case R.id.view_dialog_smartscan_tv:
                searchType = 7;
                dialog.dismiss();
                refresh();
                break;
            case R.id.view_dialog_txtscan_tv:
                searchType = 1;
                currentPathView.setText(rootpath);
                dialog.dismiss();
                refresh();
                break;
            case R.id.view_dialog_epubscan_tv:
                searchType = 3;
                currentPathView.setText(rootpath);
                dialog.dismiss();
                refresh();
                break;
            case R.id.view_dialog_umdscan_tv:
                searchType = 2;
                currentPathView.setText(rootpath);
                dialog.dismiss();
                refresh();
                break;
            case R.id.title_left:
                clickTitleBack();
                break;
            case R.id.scan_currentpath_right_tv:
                // 返回上一级
                clickParentBack();
                break;
        }
    }

    private void gotoWifi() {
        ShuqiApplication.getApplicationHandler().post(new Runnable() {
            public void run() {
                Intent intent =
                        new Intent(BookShelfFileMangementAcitvity.this, FTPTransferActivity.class);
                ActivityManager.getInstance().startNextActivity(intent,
                        BookShelfFileMangementAcitvity.this);
            }
        });
    }

    private void loadData() {
        // UserInfo user = MyAccountManager.getInstance(this);
        // if(user != null){
        // String uid = user.getUserId();
        // (ShuqiApplication.getContext(), uid);
        // }
        List<BookMarkInfo> list = BookMarkInfoDao.getInstance().getLocalBookMarkList();
        if (list != null && list.size() > 0) {
            for (BookMarkInfo info : list) {
                mAlreadyMarksSet.add(info.getFilePath());
            }
        }
    }

    private void clickTitleBack() {
        if (searchType == 0) {
            ActivityManager.getInstance().finishActivity(this);
        } else {
            searchType = 0;
            changeTitleMode(searchType);
            refresh();
        }
    }

    private boolean clickParentBack() {
        if (TextUtils.isEmpty(currentpath)) {
            return false;
        }
        File file = new File(currentpath).getParentFile();
        if (file == null) {
            return false;
        }
        onItemClickDispose(-1);
        findViewById(R.id.hint_nosdcard).setVisibility(View.GONE);
        return true;
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            findViewById(R.id.hint_nosdcard).setVisibility(View.GONE);
            if (searchType == 0) {
                boolean isRootPath = !clickParentBack();
                if (isRootPath) {
                    ActivityManager.getInstance().finishActivity(this);
                    return true;
                }
            } else {
                searchType = 0;
                changeTitleMode(searchType);
                refresh();
            }

        }
        return false;
    }

    /**
     * 
     * @param index 跳转到阅读页
     */
    public void gotoReadActivity(int index) {
        if (listdata != null && listdata.size() > index) {
            File file = new File(listdata.get(index).get("path").toString());
            if (file != null) {
                EnterBookContent.jumpToBookContentByFilePath(this, file.getPath(), BookContentActivity.INTENT_REQUEST_CODE_BOOKSHLEF);
            }
        }

    }

    /**
     * 打开对应的文件或者文件夹
     * 
     * @param index 路径存在于listdata.get(index).get("path") -1 表示去上一级目录
     */
    public void onItemClickDispose(int index) {

        if (index == -1) {
            searchType = 0;
        }

        if (listdata == null || listdata.size() <= index) {
            return;
        }
        File file = null;
        if (index == -1) {
            if (!TextUtils.isEmpty(currentpath)) {
                file = new File(currentpath).getParentFile();
            }
        } else {
            file = new File(listdata.get(index).get("path").toString());
        }
        if (file != null) {
            if (file.isDirectory()) {
                currentpath = file.getPath();
                currentPathView.setText(currentpath);
                refresh();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log4an.e("yyy", "requestCode=" + requestCode);
        if(requestCode == BookContentActivity.INTENT_REQUEST_CODE_BOOKSHLEF){
            if (resultCode == Activity.RESULT_OK) {
//                final int bookType =
//                        data.getIntExtra(BookContentActivity.INTENT_RESULT_BOOKSELF_BOOKTYPE,
//                                -1);
//                final String bookName =
//                        data.getStringExtra(BookContentActivity.INTENT_RESULT_BOOKSELF_BOOKNAME);
//
//                final String filePath =
//                        data.getStringExtra(BookContentActivity.INTENT_RESULT_BOOKSELF_FILEPATH);
//
//                final String bookId =
//                        data.getStringExtra(BookContentActivity.INTENT_RESULT_BOOKSELF_BOOKID);

                Toast.makeText(this, "书籍格式错误", Toast.LENGTH_SHORT).show();
            }
         
        }
    }


    /**
     * 底部导航的显隐，true为显示
     */
    public void showBottom(int checkedBooks, int index) {
        if (checkedBooks == 0) {
            scanBottom.setVisibility(View.GONE);
            listView.setPadding(0, 0, 0, 0);
        } else {
            scanBottom.setVisibility(View.VISIBLE);
            sureButton.setText("导入所选(" + checkedBooks + ")");
            int height = (int) getResources().getDimension(R.dimen.layout_scan_bottom_height);
            listView.setPadding(0, 0, 0, height);
            if (listdata != null && index == listdata.size() - 1) {
                // listView.scrollBy(0, Util.dip2px(shelf2, 42));
                listView.setSelection(index);
            }
        }
    }

    // 更改标题栏
    private void changeTitleMode(int searchType) {
        if (searchType == 0) {
            // 0表示正常浏览
            mTitle.setTitle("本地导入");
            mTitle.setStyle(true, true);
            mBackParentTextView.setVisibility(View.VISIBLE);
            currentPathView.setText(currentpath);
        } else {
            // 搜索
            mTitle.setTitle("扫描结果");
            mTitle.setStyle(true, false);
            int count = listdata == null ? 0 : listdata.size();
            currentPathView.setText("已扫描到文件: " + count + "个");
            mBackParentTextView.setVisibility(View.GONE);
        }
    }

    /**
     * 通知更新list
     */
    private void refresh() {
        if (listAdapter == null || rootpath == null || listdata == null) {
            return;
        }
        scanBottom.setVisibility(View.GONE);
        listView.setPadding(0, 0, 0, 0);
        if (searchType != 0) {// 搜索方式
            showDialog();
            new Thread() {
                @Override
                public void run() {
                    Runnable r1 = new Runnable() {
                        @Override
                        public void run() {
                            listdata.clear();
                            listdata.addAll(listdataTemp);
                            listdataTemp.clear();
                            if (checkHasFile()) {
                                listAdapter.notifyDataSetChanged();
                                listView.setSelection(0);
                            }
                            changeTitleMode(searchType);
                            try {
                                dismissDialog();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    };
                    int version = ScanLocalFolderTools.addNewVersion();

                    synchronized (listdataTemp) {
                        ScanLocalFolderTools.getAdapterList(rootpath, currentpath, needFileSuffix,
                                searchType, listdataTemp, BookShelfFileMangementAcitvity.this);
                    }
                    if (version == ScanLocalFolderTools.getNewVersion()) {
                        BookShelfFileMangementAcitvity.this.runOnUiThread(r1);
                    }
                }
            }.start();
        } else {// 正常切换目录
            ScanLocalFolderTools.addNewVersion();
            ScanLocalFolderTools.getAdapterList(rootpath, currentpath, needFileSuffix, searchType,
                    listdata, this);
            if (checkHasFile()) {
                listAdapter.notifyDataSetChanged();
                listView.setSelection(0);
            }
        }
    }

    private ToastDialog scaning;// 扫描的dialog

    private void showDialog() {

        if (scaning == null) {
            scaning = new ToastDialog(this);
            scaning.setOnCancelListener(new OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    searchType = 0;
                    ScanLocalFolderTools.addNewVersion();
                }
            });
        }
        scaning.setDissmisOnClickOutSide(false);
        scaning.loading("扫描中，请稍候...");
    }

    private void dismissDialog() {
        if (scaning != null) {
            scaning.dismiss();
        }

    }

    /**
     * 
     * @return true 则有文件,false没有文件
     */
    private boolean checkHasFile() {
        if (listdata.size() == 0) {
            findViewById(R.id.hint_nofile).setVisibility(View.VISIBLE);// 显示无文件提示
            return false;
        } else {
            if (findViewById(R.id.hint_nofile).getVisibility() != View.GONE) {
                findViewById(R.id.hint_nofile).setVisibility(View.GONE);
            }
            return true;
        }
    }

    // @Override
    // public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    // Log4an.i(TAG, "点击位置" + position);
    // // onItemClickDispose(position);
    // }

    @Override
    public void activityLogicForward() {}

    @Override
    public void activityInitData() {}

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (listdata != null) {
            listdata.clear();
            listdata = null;
        }

        if (listdataTemp != null) {
            listdataTemp.clear();
            listdataTemp = null;
        }

        if (mAlreadyMarksSet != null) {
            mAlreadyMarksSet.clear();
            mAlreadyMarksSet = null;
        }

        if (listAdapter != null) {
            listAdapter.dismissLoadingDialog();
        }

        if (dialog != null) {
            dialog.dismiss();
        }

        if (scaning != null) {
            scaning.dismiss();
        }
    }

    private void setScrollBar(final ListView listview, int imgId) {
        Log4an.e("CataLogLayout", "获取到的版本号：" + Util.getOSVersion());
        if (Util.getOSVersion() >= 19) {
            // setScrollBar_forSDK19(listview);
            return;
        }
        try {
            Field f = AbsListView.class.getDeclaredField("mFastScroller");
            f.setAccessible(true);
            Object o = f.get(listview);
            f = f.getType().getDeclaredField("mThumbDrawable");
            f.setAccessible(true);
            Drawable drawable = (Drawable) f.get(o);
            drawable = getResources().getDrawable(imgId);
            f.set(o, drawable);
        } catch (Exception e) {
            Log4an.e("CataLogLayout", e.toString());
        }
    }
}
